//
//  OrderListViewController.m
//  myhuibao
//
//  Created by lijun on 13-4-10.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "OrderListViewController.h"
#import <UIKit/UIKit.h>
#import "Config.h"
#import "SBJson.h"
#import "OrderCell.h"
#import "OrderDetailViewController.h"
#import "LoadMoreCell.h"
#import "OMGToast.h"
#import "MainTabViewController.h"

@interface OrderListViewController ()

@end

@implementation OrderListViewController
@synthesize mainTable;
@synthesize req;
@synthesize reqMore;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
            self.title=@"我的订单";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	if([self navigationController].viewControllers.count==1)
    {
        _btnBack.hidden=YES;
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    pageIndex=1;
    [self getOrderList];
}

-(void) getOrderList{
    NSURL *url=[NSURL URLWithString:url_orderList];
    req=[ASIFormDataRequest requestWithURL:url];
    int memberId=[[Config Instance] getMemberId];
    NSString *sid=[NSString stringWithFormat:@"%d",memberId];
    [req setPostValue:sid forKey:@"member.memberID"];
    [req setPostValue:[[Config Instance]getPassword] forKey:@"member.password"];
    [req setPostValue:[NSString stringWithFormat:@"%d",(pageIndex++)] forKey:@"pageIndex"];
    [req setShouldAttemptPersistentConnection:NO];
    [req setDidFinishSelector:@selector(finishReq:)];
    isReqFinished = false;
    [req setDelegate:self];
    
    [req startAsynchronous];

}
//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)finishReq:(ASIHTTPRequest *)request
{
    isReqFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    if(![[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"]){
        UIAlertView *view=[[UIAlertView alloc]initWithTitle:APP_TITLE message:[dic valueForKey:@"log"]==[NSNull null]?@"未获取到订单信息":[dic valueForKey:@"log"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
        return;
    }
    if([dic valueForKey:@"data"] !=[NSNull null])
        tableDataArray = [dic valueForKey:@"data"];
    returnCount = [tableDataArray count];
    if (returnCount==0) {
        [OMGToast showWithText:@"无订单记录。" bottomOffset:100];
    }
    [mainTable reloadData];
    [mainTable setContentOffset:CGPointMake(0, 0)];
    [Config setExtraCellLineHidden:mainTable];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
    isReqFinished = true;
    isReqMoreFinished = true;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    if (count>=pageSize) {
        return count+1;
    }else
        return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] < ([tableDataArray count])) {
        return 60;
    }else{
        return 40;
    }
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"OrderCell";
    if([indexPath row] < ([tableDataArray count])) {
        
        OrderCell *cell = (OrderCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell==nil)
        {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"OrderCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleGray];

        }
                NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
//        NSLog(@"%@",item);
        cell.merchantName.text = [item valueForKey:@"merchant"];
        NSString *status =  [item valueForKey:@"status"];
        cell.orderStatus.text =status;
        if ([status isEqualToString:@"预定"]) {
            cell.orderStatus.backgroundColor=[UIColor colorWithRed:210/255.0 green:126/255.0 blue:72/255.0 alpha:1];
            cell.orderStatus.text =@"预定待确认";
        }else if ([status isEqualToString:@"成功"]) {
            cell.orderStatus.backgroundColor=[UIColor colorWithRed:253/255.0 green:103/255.0 blue:7/255.0 alpha:1];
        }else if ([status isEqualToString:@"已取消"]) {
            cell.orderStatus.backgroundColor=[UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1];
        }else if ([status isEqualToString:@"失败"]) {
            cell.orderStatus.backgroundColor=[UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
        }else
            cell.orderStatus.backgroundColor=[UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:1];
        cell.orderValue.text = [item valueForKey:@"typeName"] ;
        NSString *bookDate=[[item valueForKey:@"bookingTime"] stringByReplacingOccurrencesOfString:@"T" withString:@" "];
        cell.bookTime.text =bookDate;
        return cell;
        
    }else{
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        if(returnCount<pageSize){
            cell.lbText.text=@"";
            cell.hidden = true;
        }else{
            //创建loadMoreCell
            cell.lbText.text=str_more;
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.detailTextLabel.text=@"";
        cell.imageView.image =nil;
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == [tableDataArray count]) {
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?pageIndex=%d",url_orderList,pageIndex++]] ;
        reqMore = [ASIFormDataRequest requestWithURL:url];
        int memberId=[[Config Instance] getMemberId];
        NSString *sid=[NSString stringWithFormat:@"%d",memberId];
        [reqMore setPostValue:sid forKey:@"member.memberID"];
        [reqMore setPostValue:[[Config Instance]getPassword] forKey:@"member.password"];
        [reqMore setShouldAttemptPersistentConnection:NO];
        [reqMore setDidFinishSelector:@selector(appendTableWith:)];
        reqMore.delegate = self;
        isReqMoreFinished = false;
        [reqMore startAsynchronous];
//        NSString *jsonStr = [request responseString];
//        
//        NSDictionary *dic = [jsonStr JSONValue];
//        NSMutableArray *array = [dic valueForKey:@"data"];
//        returnCount = [array count];
//        [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
        return;
    }else{
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        OrderDetailViewController *view=[[OrderDetailViewController alloc]initWithNibName:@"OrderDetailViewController" bundle:nil];
        view.orderNoId=[item valueForKey:@"orderNO"];
        view.orderType=[[item valueForKey:@"typeID"]intValue];
        view.merchantId = [[item valueForKey:@"merchantID"]intValue];
        [self.navigationController pushViewController:view animated:YES];
    }
}

-(void) appendTableWith:(ASIHTTPRequest *)request
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    isReqMoreFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSArray *data = [[NSArray alloc]init];
    if([dic valueForKey:@"data"] !=[NSNull null])
        data = [dic valueForKey:@"data"];
    returnCount = [data count];
    //    [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    if ([data count]==0) {
        [self.mainTable reloadData];
    }
    //重新调用UITableView的方法, 来生成行.
    [self.mainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
    //    isSearchMoreFinished = true;
}

- (IBAction)doBack:(id)sender {
    if (!isReqFinished){
        [req clearDelegatesAndCancel];
        [req cancel];
    }
    if (!isReqMoreFinished){
        [reqMore clearDelegatesAndCancel];
        [reqMore cancel];
    }

    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidUnload
{
    [self setMainTable:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    MainTabViewController * tab=(MainTabViewController*)[self tabBarController];
    UICustomTabBar *item=[[tab customTabBarItems] objectAtIndex:2];
    [item switchToNormalState];
    [[self tabBarController] setSelectedIndex:3];
    [[[tab customTabBarItems] objectAtIndex:3] switchToClickedState];
}
@end
